import { useMemo, useReducer } from "react";
export function useVm(rawState, rawFn, reducer) {
  let methodNames = Object.keys(rawFn);
  let [state, dispatch] = useReducer(reducer, rawState);

  // 构建返回的新fn
  let fn=useMemo(()=>{
    let fns = {};
    methodNames.forEach((name) => {
      if(name.endsWith("Async")|| name.endsWith("$")){
        fns[name] = (...payload)=>{
          rawFn[name](state,...payload).then(result=>{
            dispatch({type:"__load",payload:[result]})
          })
        }
      }else{
        fns[name] = (...payload) => {
          dispatch({ type: name, payload });
        };
      }
    });
    return fns
  })
   
  return { state, fn };
}

export function genReducer(rawFn) {
  if (!rawFn.__load) {
    rawFn.__load = (_, v) => v;
  }
  function reducer(preState, { type, payload }) {
    // type是自动生成的，所以无须再判断是否存在
    let newState = rawFn[type](preState, ...payload);
    return { ...preState, ...newState };
  }
  return reducer;
}
